package com.atguigui.leetcode;

/**
 * 1592.重新排列单词间的空格
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/9/7 13:03
 */
public class P1592RearrangeSpacesBetweenWords {
    public static void main(String[] args) {
        Solution solution = new P1592RearrangeSpacesBetweenWords().new Solution();
        // TO TEST
    }


    class Solution {
        public String reorderSpaces(String text) {
            int length = text.length();
            String[] words = text.trim().split("\\s+");
            //计算空格的数量
            int cntSpace = length;
            for (String word : words) {
                cntSpace -= word.length();
            }
            StringBuilder sb = new StringBuilder();
            //判断特殊情况
            if (words.length == 1) {
                sb.append(words[0]);
                //将所有的空格拼接到最后
                for (int i = 0; i < cntSpace; i++) {
                    sb.append(' ');
                }
                return sb.toString();
            }

            //平均一下每个单词单词后的空格数
            int perSpace = cntSpace / (words.length - 1);
            //平均后剩余的空格数
            int restSpace = cntSpace % (words.length - 1);
            for (int i = 0; i < words.length; i++) {
                if (i > 0) {
                    for (int j = 0; j < perSpace; j++) {
                        sb.append(' ');
                    }
                }
                sb.append(words[i]);
            }
            //将剩下的空格拼接在末尾
            for (int i = 0; i < restSpace; i++) {
                sb.append(' ');
            }
            return sb.toString();
        }
    }
}
